﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using System.Data;
using System.IO;
using System.Drawing;
public partial class administrator_uc_admin_v_news : WebPageSecurity
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CommonBLL.RegisterCKFinder(CKEditorBody);
            PanelEdit.Visible = false;
            if (!string.IsNullOrEmpty(Request.QueryString["itemid"]))
            {
                LoadDataInfo(int.Parse(Request.QueryString["itemid"].ToString().Trim()));               
            }
        }
    }
    private void LoadDataInfo(int ItemID)
    {
        DataTable dt = new BLL.CmsBLL().News_ViewItemByID(ItemID);
        if (dt.Rows.Count > 0)
        {
            ltNewsID.Text = dt.Rows[0]["NewsID"].ToString();
            hdItemID.Value = dt.Rows[0]["NewsID"].ToString();
            if (int.Parse("0" + dt.Rows[0]["CateID"].ToString()) > 0)
                ltCateName.Text = new BLL.CmsBLL().GroupNews_GetTitle((int)dt.Rows[0]["CateID"]);
            ltTitle.Text = dt.Rows[0]["Title"].ToString();
            ltDescription.Text = dt.Rows[0]["Description"].ToString();            
            ltBody.Text = dt.Rows[0]["Body"].ToString();
            ltAuthor.Text = dt.Rows[0]["Author"].ToString();
            ltSource.Text = dt.Rows[0]["Source"].ToString();
            ltActive.Text = dt.Rows[0]["_Active"].ToString();
            LoadImage(ltImage, dt.Rows[0]["Image"].ToString());
        }
        else
            lblMessageView.Text = "Load dữ liệu lỗi!";
    }
    private void LoadImage(Literal ltcontrol, string FileName)
    {
        try
        {
            ltcontrol.Text = "<img src=\"../smallimages/" + FileName + "\" />\n";
        }
        catch (Exception ex)
        {
            ltcontrol.Text = "Load image error! " + ex.Message;
        }
    }
    protected void btnEditItem_Click(object sender, EventArgs e)
    {
        PanelView.Visible = false;
        PanelEdit.Visible = true;
        LoadDataToDropDownList(DropdownParentID, 0);
        LoadDataInfoEdit(int.Parse("0"+hdItemID.Value));     
    }
    private void LoadDataToDropDownList(DropDownList cboName, int CateID)
    {
        ListItem list = new ListItem();
        cboName.Items.Clear();
        cboName.Items.Add(list);
        list.Selected = true;
        list.Value = "0";
        list.Text = "---Chọn nhóm tin---";
        DataTable dtb = new CmsBLL().GroupNews_GetTreeActive(CateID);
        if (dtb.Rows.Count > 0)
        {
            new CommonBLL().LoadDropDonwList(cboName, dtb, "_Title", "CateID");
        }
    }
    private void LoadDataInfoEdit(int ItemID)
    {
        DataTable dt = new BLL.CmsBLL().News_ViewItemByID(ItemID);
        if (dt.Rows.Count > 0)
        {         
            DropdownParentID.SelectedValue = dt.Rows[0]["CateID"] + "";
            txtTitle.Text = dt.Rows[0]["Title"].ToString();
            CKEditorDescription.Text = dt.Rows[0]["Description"].ToString();
            CKEditorBody.Text = dt.Rows[0]["Body"].ToString();
            txtSource.Text = dt.Rows[0]["Source"].ToString();
            rdActive.SelectedValue = dt.Rows[0]["Active"] + "";
            LoadImage(ltViewImage, dt.Rows[0]["Image"].ToString());
        }
        else
            lblMessageEdit.Text = "Load data failt!";
    }      
    protected void lbtUpdateItem_Click(object sender, EventArgs e)
    {
        if (DropdownParentID.SelectedValue == "0")
        {
            lblMessageEdit.Text = "Bạn chưa chọn nhóm tin!";
            return;
        }
        if (FileUploadImage.HasFile)
        {
            string strFileName = FileUploadImage.FileName;
            try
            {
                strFileName = FileUploadImage.FileName;
                Stream fStream = FileUploadImage.FileContent;
                strFileName = FileUploadImage.FileName.Replace(' ', '_');
                strFileName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
                strFileName = CommonBLL.GetFilename(strFileName);

                string filepathsmallimage = Server.MapPath("" + DAL.EnvInfo.PathUpload + "smallimages//") + strFileName;
                //string filepathlargeimage = Server.MapPath("~/images//") + strFileName;

                // Validate the uploaded file
                // 1. The uploaded file should not be a blank file
                if (FileUploadImage.FileBytes.Length == 0)
                {
                    lblMessageEdit.Text = "File bạn chọn bị lỗi! dung lượng file = " + FileUploadImage.FileBytes.Length.ToString() + " bytes";
                    return;
                }
                // 2. The uploaded file should be having one of the allowed extensions
                string ext = System.IO.Path.GetExtension(FileUploadImage.FileName).TrimStart(".".ToCharArray()).ToLower();
                if ((ext != "jpeg") && (ext != "jpg") && (ext != "png") && (ext != "gif") && (ext != "bmp"))
                {
                    lblMessageEdit.Text = "Định dạng file bạn chọn không hợp lệ (File hợp lệ dạng Ảnh)";
                    return;
                }

                // Validation successful
                // Load the image into Bitmap Object

                Bitmap uploadedImage = new Bitmap(FileUploadImage.FileContent);

                // Set the maximum width and height here.
                // You can make this versatile by getting these values from
                // QueryString or textboxes
                int maxWidth = 145;
                int maxHeight = 110;

                // Resize the image
                Bitmap resizedImage = CommonBLL.GetScaledPicture(uploadedImage, maxWidth, maxHeight);

                //Save the image
                // String virtualPath = "~/temp/" + System.Guid.NewGuid().ToString() + "." + ext;
                //String tempFileName = Server.MapPath(virtualPath);
                resizedImage.Save(filepathsmallimage, uploadedImage.RawFormat);
                new CmsBLL().News_UpDateItem(int.Parse(hdItemID.Value), int.Parse("0" + DropdownParentID.SelectedValue), txtTitle.Text, CKEditorDescription.Text + "", CKEditorBody.Text + "", "", strFileName, DateTime.Now, txtSource.Text, int.Parse("0" + rdActive.SelectedValue));
                DataTable dt = new CmsBLL().News_ViewItemByID(int.Parse("0" + hdItemID.Value));
                if (dt.Rows.Count > 0)
                    LoadImage(ltViewImage, dt.Rows[0]["Image"].ToString());
                lblMessageEdit.Text = "Cập nhật thành công!";
                //FileUploadNews.SaveAs(filepathlargeimage);               
                // Load the resized image on the browser
                //picture.ImageUrl = virtualPath;
                //imageContainer.Visible = true;
            }
            catch (Exception ex)
            {
                lblMessageEdit.Text = "ERROR! " + ex.Message.ToString();
            }

        }
        else
        {
            try
            {
                new CmsBLL().News_UpDateItem(int.Parse(hdItemID.Value), int.Parse("0" + DropdownParentID.SelectedValue), txtTitle.Text, CKEditorDescription.Text + "", CKEditorBody.Text + "", "", "", DateTime.Now, txtSource.Text, int.Parse("0" + rdActive.SelectedValue));
                lblMessageEdit.Text = "Cập nhật thành công!";

            }
            catch (Exception ex)
            {
                lblMessageEdit.Text = "ERROR! " + ex.Message.ToString();
            }
        } 
    }
}